<template>
  	<div class="cart_main">
		<!-- 判断购物车是否有数据 -->
		<div v-if="listData.length !==0">
			<div class="top">
				<div class="numbers">
					购物数量&nbsp;<span>{{allnumber}}</span>
				</div>
				<!-- 管理 -->
				<div class="del_cart">
					<div class="del" @click="changeManage" v-if="manageState">
						管理
					</div>
					<div class="del" @click="changeManage" v-else>
						完成
					</div>
				</div>
			</div>

			<!-- 购物车列表 -->
		    <div class="cartlist">
		      	<div class="item" v-for="(item, index) in listData" :key="index" >
			        <div class="con">
			          	<div class="left">
			          		<!-- 选中的图标 -->
			            	<div class="icon" @click="oneCheck(index, item.goods_id)" 
			            	 	:class="[checkId[index] ? 'active' : '']">
			            	</div>
				            <div class="img" @click="goodsDetail(item.goods_id)">
				              	<img :src="item.list_pic_url" alt="">
				            </div>
				            <div class="info" @click="goodsDetail(item.goods_id)">
				              	<p class="name">{{item.goods_name}}</p>
				              	<p class="price">¥{{item.retail_price}}</p>
				            </div>
				        </div>
				        <div class="right">
				          	<div class="reduce" @click="reduce(item.goods_id,index)">-</div>
				          	<!-- disabled="false"实现输入框里不能聚焦 -->
				          	<input type="text" class="number" v-model="item.number"
				          	 disabled="false">
				          	<div class="add" @click="add(item.goods_id)">+</div>
				        </div>
			        </div>
		      	</div>
		    </div>
			<!-- 底部操作 -->
		    <div class="fixed">
		      	<div class="left" @click="allCheck" :class="{'active': allcheck}">
		        	全选({{isCheckedNumber}})
		      	</div>
		      	<div class="right">
		        	<div v-if="cartState" class="a">
			        	<div class="allprice">¥{{allPrice}}</div>
						<div class="orderdown" @click="orderDown">下单</div>
			        </div>
			        <div v-else class="b">
			        	<div class="del" @click="cartDel">删除</div>
			        </div>
		      	</div>
	    	</div>
		</div>
		<!-- 购物车无数据 -->
		<div class="no_catr" v-else>
			<img src="http://r.photo.store.qq.com/psc?/V13kx5iq3fGNrB/h4SLI6MeeCc7mRdKk01usoygd.UAD7v6p6FMPb9lg0Oz56o9EAY5N9n4q85RUCnIKtmwuYi*NMAzG8jQT5hiP68nj6dxtzi78cCgUQhMWH4!/r">
			<div>暂无商品，快去逛逛吧~</div>
		</div>
  	</div>
</template>

<script>
import {get,post} from '@/util'
export default {
  	data () {
	    return {
	    	cartState:true,
	    	manageState:true,
	     	openId: '',
	      	listData: [],//存放购物车信息
	      	checkId: [], //存放点击单选或多选时的item下标和商品id
	      	allcheck: false,
	      	allnumber:'' //购物车总数
	    }
  	},
  	onShow () {
  		const userinfo = wx.getStorageSync('userinfo')
	    this.openId = userinfo.openId
	    this.checkId=[]
	    this.getListData()

  	},
  	methods: {
  		//获取购物车数据
	    async getListData () {
	    	// console.log("this.openId",this.openId)
	      	const data = await get('/app/cart/cartList', {
	        	openId: this.openId
	      	})
	      	this.listData = data.cartList
	      	// console.log("this.listData",data.cartList)
	      	this.allnumber = data.allnumber
	    },
	    //单选  
	    oneCheck (index, id) {
	    	// 如果在checkId数组第index个中有存在与点击单选时有相同的商品id
	      	if (this.checkId[index]) { 
	      		//将其中的商品id置为false,取消了单选
	        	this.$set(this.checkId, index, false)
	      	} else {
	      		//否则将商品id的值写入checkId数组的第index个下标里
	        	this.$set(this.checkId, index, id)
	      	}
	    },
	    // 全选
	    allCheck () {
	      	// 先清空选择
	      	this.checkId = []
	      	// 如果全选的状态为true，将设为false
	      	if (this.allcheck) {
	        	this.allcheck = false
	      	} else {
	      		// 全部选择
	        	this.allcheck = true
	        	// 循环，取到listData数组的信息
	        	for (let i = 0; i < this.listData.length; i++) {
		          	const data = this.listData[i]
		          	// 将listData数组中的商品id的值放入到checkId中
		          	this.checkId.push(data.goods_id)
		        }
	      	}
	    },
	    // 管理购物车
	    changeManage(){
	    	this.cartState = !this.cartState
	    	this.manageState = !this.manageState
	    },
	    // 下单
	    async orderDown () {
      		if (this.checkId.length == 0) {
        		wx.showToast({
          			title: '请选择商品',
          			icon: 'none',
          			duration: 1500
        		})
       	 		return false
      		}
      		// 去除数组中空的false
      		let newgoodsid = []
      		for (let i = 0; i < this.checkId.length; i++) {
        		const element = this.checkId[i]
        		if (element) {
          			newgoodsid.push(element)
        		}
      		}
      		let goodsId = newgoodsid.join(',')
      		// 向订单表更新或插入数据
      		const data = await post('/app/order/submitAction', {
        		goodsId: goodsId,
        		openId: this.openId,
        		allPrice: this.allPrice
     		})
      		if (data) {
        		wx.navigateTo({
          			url: '/pages/toOrder/main'
        		});
      		}
    	},
    	//删除
    	cartDel(){
    		if (this.checkId.length == 0) {   			
        		wx.showToast({
          			title: '请选择商品',
          			icon: 'none',
          			duration: 1500
        		})
       	 		return false
			}
      		wx.showModal({
			  	title: '确定要删除该商品吗？',
			  	showCancel:true,
			  	success: (res) => {
      				if(res.confirm){
      					this.delCarts()
      				}		
	        	} 
			})  		
	    },
	    async delCarts(){
	    	// 去除数组中空的false
      		let newgoodsid = []
      		for (let i = 0; i < this.checkId.length; i++) {
        		const element = this.checkId[i]
        		if (element) {
          			newgoodsid.push(element)
        		}
      		}
      		let goodsId = newgoodsid.join(',')
      		// console.log("goodsId:",goodsId)
	    	// 删除选中的购物车信息
      		const data = await post('/app/cart/delCart',{
      			goodsId: goodsId,
      			openId: this.openId
      		})
      		if(data){
      			wx.showToast({
          			title: '购物车删除成功',
          			icon: 'none',
          			duration: 2000
        		}) 
        		this.checkId = []
        		this.getListData()			
      		}else{
      			console.log("购物车删除失败")
      		} 
	    },
	    //添加数量
	    async add(id){
	    	const data = await post('/app/cart/cartNumber',{
	    		openId: this.openId,
	    		goodsId: id,
	    		flag:true
	    	})
	    	this.getListData()
	    },
	    //减少数量
	    async reduce(id,index){
	    	if(this.listData[index].number == 1){
	    		wx.showToast({
          			title: '不能再减了哦~',
          			icon: 'none',
          			duration: 2000
        		})
	    	}else{
		    	const data = await post('/app/cart/cartNumber',{
		    		openId: this.openId,
		    		goodsId: id,
		    		flag:false
		    	})
		    	this.getListData()
	    	}	    	
	    },
	    //跳转到商品详情页面
   	 	goodsDetail (id) {
      		wx.navigateTo({
        		url: '/pages/goods/main?id=' + id
      		});
    	}
  	},
	computed: {
		//计算选择的购物车数量
	    isCheckedNumber () {
	      	let number = 0
	      	//循环，看选择了有多少件购物车
	      	for (let i = 0; i < this.checkId.length; i++) {
	        	if (this.checkId[i]) {
	        		number++
	        	}
	      	}
	      	//如果单选选择的总件数等于listData数组里的总长度
	      	if (number == this.listData.length && number !== 0) {
	      		//将勾选全选按钮
	        	this.allcheck = true
	      	} else {
	      		//将全选按钮取消勾选
	        	this.allcheck = false
	      	}
	     	return number
	    },
	    //计算选择的总价格
	    allPrice () {
	      	let Price = 0
	      	//循环，看选择了多少
	      	for (let i = 0; i < this.checkId.length; i++) {	      		
	        	if (this.checkId[i]) {
	          		Price += this.listData[i].retail_price * this.listData[i].number
	        	}
	      	}
	      	return Price
	    }
	}
}
</script>
/*
146	o_MyB4jDjNC9HMf-CDmLApTovzro	1019006	植物填充护颈夜交藤枕	99	1	http://yanxuan.nosdn.127.net/60c3707837c97a21715ecc3986a744ce.png
147	o_MyB4jDjNC9HMf-CDmLApTovzro	1010001	澳洲纯羊毛盖毯 舒适款	299	1	http://yanxuan.nosdn.127.net/a8b0a5def7d64e411dd98bdfb1fc989b.png
148	o_MyB4jDjNC9HMf-CDmLApTovzro	1011004	色织精梳AB纱格纹空调被	199	1	http://yanxuan.nosdn.127.net/0984c9388a2c3fd2335779da904be393.png
149	o_MyB4jDjNC9HMf-CDmLApTovzro	1036002	高山苦荞麦枕	99	1	http://yanxuan.nosdn.127.net/ffd7efe9d5225dff9f36d5110b027caa.png

 */

<style lang="scss" scoped>
@import "./cart.scss";
</style>